package org.openzip.openzip.unpacking.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class JarToFolderCopier {
	
	public JarToFolderCopier() {
		//	
	}
	
	public boolean copy(JarFile jarFrom, File dirTo) {
		
		Enumeration entries = jarFrom.entries();
		while (entries.hasMoreElements()) {
		    ZipEntry entry = (ZipEntry) entries.nextElement();
			System.out.println(entry.toString());
			
			
			InputStream inp = null;
			try {
				 inp = jarFrom.getInputStream(entry);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(entry.toString().startsWith("data/")) {
				String relPath = entry.toString();
				String cleanPath = relPath.substring(5); // 5 - d a t a /
				this._copyfile(inp, dirTo.getAbsolutePath(), cleanPath);
			}
			
		}
		
	
		return true;
	}
	
	private void _copyfile(InputStream in, String dtFile, String cleanPath){
		    try{	
		      
		      String newPath = dtFile + "/" + cleanPath;	
		      System.out.println("Clean path: " + cleanPath);
		      
		      File f2 = new File(newPath);
		      
		      
		      System.out.println("Parent: " + f2.getParentFile().getAbsolutePath());
		      f2.getParentFile().mkdirs();

		      
		      //For Append the file.
//		      OutputStream out = new FileOutputStream(f2,true);

		      //For Overwrite the file.
		      OutputStream out = new FileOutputStream(f2);

		      byte[] buf = new byte[1024];
		      int len;
		      while ((len = in.read(buf)) > 0){
		        out.write(buf, 0, len);
		      }
		      in.close();
		      out.close();
		      System.out.println("File copied.");
		    }
		    catch(FileNotFoundException ex){
		      System.out.println(ex.getMessage() + " in the specified directory.");
		      System.exit(0);
		    }
		    catch(IOException e){
		      System.out.println(e.getMessage());      
		    }
		  }
}
